using System;
using System.IO;
using System.Reflection;

namespace WHC.OrderWater.Commons
{
    /// <summary>
    /// This class provides some utility method to operate the xml file.
    /// </summary>
    public sealed class XmlUtils
    {
        private XmlUtils()
        {
        }

        /// <summary>
        /// Gets the object form the xml file.
        /// </summary>
        /// <param name="path">The xml file path.</param>
        /// <param name="type">The object type.</param>
        /// <returns>The object deserialized from the xml file.</returns>
        public static object LoadObjectFromXml(string path, Type type)
        {
            object obj = null;
            using (StreamReader reader = new StreamReader(path))
            {
                string content = reader.ReadToEnd();
                obj = XmlConvertor.XmlToObject(content, type);
            }
            return obj;
        }

        /// <summary>
        /// Saves the object to specified xml file.
        /// </summary>
        /// <param name="path">The xml file path.</param>
        /// <param name="obj">The object to save.</param>
        public static void SaveObjectToXml(string path, object obj)
        {
            string xml = XmlConvertor.ObjectToXml(obj, true);
            using (StreamWriter writer = new StreamWriter(path))
            {
                writer.Write(xml);
            }
        }

        /// <summary>
        /// Gets the text string from the file.
        /// </summary>
        /// <param name="path">The file path.</param>
        /// <returns>The text string in the file.</returns>
        public static string ReadFile(string path)
        {
            string content = string.Empty;
            using (StreamReader reader = new StreamReader(path))
            {
                content = reader.ReadToEnd();
            }
            return content;
        }

        /// <summary>
        /// Gets the text string from embedded resource(e.g: xml).
        /// </summary>
        /// <param name="fileWholeName">The resource file name including the namespace of the project.</param>
        /// <returns>The text string in the resource.</returns>
        public static string ReadFileFromEmbedded(string fileWholeName)
        {
            string result = string.Empty;

            using (TextReader reader = new StreamReader(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(fileWholeName)))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
    }
}